import React,{ useState, useEffect } from 'react';
import { Form,Input,Select,Radio,Button,Upload,message,Modal,Image } from 'antd';
import { InboxOutlined,DeleteOutlined } from '@ant-design/icons';
import axios from '../axios/index';
import './PetInfo.css'
import userStore from '../stores/UserStore';
import { useNavigate } from 'react-router-dom';

const { Option } = Select;
const { Dragger } = Upload;
function PetInfo() {
    const [form] = Form.useForm();
    const [speciesOptions, setSpeciesOptions] = useState([]);
    const [fileList, setFileList] = useState([]);
    const navigate = useNavigate();
    const handleClick = function(path){
        navigate(path);
    }

    useEffect(() => {
        // 从后台获取宠物种类数据
        axios.get('/petType/getAll')
            .then(response => {
                // console.log('后端返回的数据:', response.data);
                setSpeciesOptions(response.data.data);
            })
            .catch(error => {
                console.error('获取宠物种类失败:', error);
                message.error('获取宠物种类失败，请稍后再试');
            });
    }, []);

    const onFinish = async (values) => {
        const { imgs,...formData } = values;
        console.log('Received values of form: ', formData);
        const userId = userStore.getUser().id;
        const dataToSend = {
            ...formData,
            petUserId: userId,
        };
        try {
            // 发送表单数据到后端
            const petResponse = await axios.post('/pet/add', dataToSend);
            console.log('宠物信息提交成功:', petResponse);
            message.success('宠物信息提交成功');
    
            const petId = petResponse.data.data.petId;
    
            // 发送图片 URL 和 pet_id 到后端
            if (fileList && fileList.length > 0) {
                const imgData = fileList.map(img => ({
                    imgUrl: img.url,
                    imgPetId: petId,
                }));
    
                const imgResponse = await axios.post('/imgs/add', imgData, {
                    headers: {
                        'Content-Type': 'application/json'
                    }
                });
                console.log('图片信息提交成功:', imgResponse);
                message.success('图片信息提交成功');
            }
    
            form.resetFields(); // 重置表单
            setFileList([]); // 重置 fileList

            navigate('/adoptcenter');
        } catch (error) {
            console.error('宠物信息提交失败:', error);
            message.error('宠物信息提交失败，请稍后再试');
        }
    };

    const handleRemove = (file) => {
        const index = fileList.indexOf(file);
        const newFileList = fileList.slice();
        newFileList.splice(index, 1);

        // 发送删除请求到后端
        axios.post('/oss/delete', { objectNames: [`imgs/${file.name}`] })
            .then(response => {
                console.log('文件删除成功:', response);
                message.success('文件删除成功');
                setFileList(newFileList);
            })
            .catch(error => {
                console.error('文件删除失败:', error);
                message.error('文件删除失败，请稍后再试');
            });
    };

    const beforeUpload = (file) => {
        const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
        if (!isJpgOrPng) {
            message.error('只能上传 JPG/PNG 文件!');
        }
        const isLt2M = file.size / 1024 / 1024 < 2;
        if (!isLt2M) {
            message.error('图片必须小于 2MB!');
        }
        return isJpgOrPng && isLt2M;
    };

    const customRequest = ({ file, onSuccess }) => {
        const formData = new FormData();
        formData.append('files', file);

        axios.post('/oss/upload', formData, {
            headers: {
                'Content-Type': 'multipart/form-data'
            }
        })
        .then(response => {
            console.log('文件上传成功:', response);
            message.success('文件上传成功');
            if (response.data && response.data.code === 2000 && response.data.data) {
                console.log(response.data);
                const url = response.data.data[0];setFileList(prevFileList => [
                    ...prevFileList,
                    {
                        uid: -Math.random().toString(36).substr(2, 9), // 随机生成一个唯一的uid
                        name: url.split('/').pop(), // 文件名
                        status: 'done', // 状态为完成
                        url: url, // 图片的URL
                    }
                ]);
                onSuccess({ url: url }, file);
            } else {
                console.error('上传文件失败: 数据格式不正确', response.data);
                message.error('上传文件失败，请稍后再试');
            }
        })
        .catch(error => {
            console.error('文件上传失败:', error);
            message.error('文件上传失败，请稍后再试');
        });
    };

    return (
        <div className='container'>
            <div className='petInfoContent'>
            <Form form={form} onFinish={onFinish} layout="horizontal" size='large'
                labelCol={{ span: 6 }} wrapperCol={{ span: 18 }}
                className='form-container'>
                    <h1>待领养宠物信息填写</h1>
                    <Form.Item name="petTypeId" label="宠物种类" rules={[{ required: true, message: '请选择宠物种类' }]}>
                        <Select placeholder="请选择宠物种类">
                        {speciesOptions.map(option => (
                            <Option key={option.typeId} value={option.typeId}>
                                {option.typeName}
                            </Option>
                        ))}
                        {/* <Option value="dog">狗</Option>
                        <Option value="cat">猫</Option>
                        <Option value="other">其他</Option> */}
                        </Select>
                    </Form.Item>

                    <Form.Item name="petVariety" label="宠物品种" rules={[{ required: true, message: '请输入宠物品种' }]}>
                        <Input placeholder="请输入宠物品种" />
                    </Form.Item>

                    <Form.Item name="petName" label="宠物名字" rules={[{ required: true, message: '请输入宠物名字' }]}>
                        <Input placeholder="请输入宠物名字" />
                    </Form.Item>

                    <Form.Item name="petSexId" label="宠物性别" rules={[{ required: true, message: '请选择宠物性别' }]}>
                        <Radio.Group>
                            <Radio value={3}>妹妹</Radio>
                            <Radio value={4}>弟弟</Radio>
                        </Radio.Group>
                    </Form.Item>

                    <Form.Item name="petAge" label="宠物年龄" rules={[{ required: true, message: '请输入宠物年龄' }]}>
                        <Input placeholder="请输入宠物年龄(例:1岁1个月1天)" />
                    </Form.Item>

                    <Form.Item name="petDescribe" label="宠物描述" rules={[{ required: true, message: '请输入宠物描述' }]}>
                        <Input.TextArea rows={4} placeholder="请输入宠物描述" />
                    </Form.Item>

                    <Form.Item name="imgs" label="宠物照片" rules={[{ required: true, message: '请上传宠物照片' }]} className="form-item-spacing">
                        {/* <input type='file' onChange={upload} accept='image/jpeg,image/png' multiple></input> */}
                        <Upload
                            listType="picture-card"
                            fileList={fileList}
                            customRequest={customRequest}
                            beforeUpload={beforeUpload}
                            onRemove={handleRemove}
                        >
                            {fileList.length >= 5 ? null : <InboxOutlined />}
                        </Upload>
                    </Form.Item>

                    <Form.Item className="button-container">
                        <Button type="primary" htmlType="submit">
                            发布
                        </Button>
                        <Button onClick={()=>handleClick('/home')} style={{ marginLeft: 8 }}>
                            取消
                        </Button>
                    </Form.Item>
                </Form>
            </div>
        </div>
    )
}

export default PetInfo;